<?php
include_once 'checkAdmin.php';
$carName = $_POST['carName'];
$carDesc = $_POST['carDesc'];
switch ($_FILES['carPic']['error']) {
    case 0:
        //没有错误
        upload();
        break;
    case 1:
        echo "<script>alert('上传的文件超过了 php.ini 中 upload_max_filesize选项限制的值。');history.back();</script>";
        break;
    case 2:
        echo "<script>alert('上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。');history.back();</script>";
        break;
    case 3:
        echo "<script>alert('文件只有部分被上传。');history.back();</script>";
        break;
    case 4:
        echo "<script>alert('车辆图片必须要选择。');history.back();</script>";
        break;
    case 6:
        echo "<script>alert('找不到临时文件夹');history.back();</script>";
        break;
    case 7:
        echo "<script>alert('文件写入失败');history.back();</script>";
        break;
}
function upload() {
    if($_FILES['carPic']['size'] > 2048*1024){
        //图片文件不能大于2MB
        echo "<script>alert('文件大小不能超过2MB');history.back();</script>";
        exit;
    }
    //接下来判断文件格式
    $allowType = array('image/gif','image/png','image/jpg','image/jpeg');
    if(!in_array($_FILES['carPic']['type'],$allowType)){
        echo "<script>alert('文件类型只能是jpg、jpeg、gif、png');history.back();</script>";
        exit;
    }
    $allowExt = array('gif','png','jpg','jpeg');
    $fileName = $_FILES['carPic']['name'];
    $fileNameArray = explode('.',$fileName);
    $ext = end($fileNameArray);//拿到文件的扩展名
    if(!in_array(strtolower($ext),$fileNameArray)){
        echo "<script>alert('文件扩展名只能是' . implode('、',$allowExt));history.back();</script>";
        exit;
    }
    $fileName = uniqid('',true).".".$ext;
    if(!move_uploaded_file($_FILES['carPic']['tmp_name'],"./img/" . $fileName)){
        echo "<script>alert('文件上传失败');history.back();</script>";
        exit;
    }
    //说明文件上传正常，接下来插入数据库即可

}